package com.mifengs.mall.ui.login;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.TextInputLayout;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.ui.web.CommonWebActivity;
import com.mifengs.mall.util.PwdCheckUtil;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.VerifyCodeView;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterStepOneActivity extends BaseActivity<RegisterPresent> implements RegisterContract.View {

    @BindView(R.id.rl_quit)
    RelativeLayout mRlQuit;
    @BindView(R.id.btn_refresh)
    ImageButton mBtnRefresh;
    @BindView(R.id.bt_register)
    Button mBtRegister;
    @BindView(R.id.btn_code)
    Button mBtnCode;
    @BindView(R.id.btn_agreement)
    Button mAgreement;
    @BindView(R.id.inputLayout_code)
    TextInputLayout mInputLayoutCode;
    @BindView(R.id.checkbox)
    CheckBox mCheckbox;
    @BindView(R.id.inputLayout_pwd)
    TextInputLayout mInputLayoutPwd;
    @BindView(R.id.iv_xianshi)
    ImageView mIvXianshi;
    @BindView(R.id.inputLayout_phone)
    TextInputLayout mInputLayoutPhone;
    @BindView(R.id.inputLayout_photo_code)
    TextInputLayout mInputLayoutPhotoCode;
    @BindView(R.id.btn_photo_code)
    VerifyCodeView mPhotoCodeWebView;
    @BindView(R.id.ll_share)
    LinearLayout mLlShare;
    @BindView(R.id.tv_shareId)
    TextView mTvShareId;
    @BindView(R.id.psw_edit)
    EditText mPswEdit;
    @BindView(R.id.relative_phone_del)
    RelativeLayout relativePhoneDel;
    @BindView(R.id.relative_pwd_del)
    RelativeLayout relativePwdDel;
    private boolean mDisplayFlg = false;
    private MyTime myTime;
    private boolean isCheckbox = true;
    private boolean isPhone = true;
    private String mShareId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_step_one);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.light_yellow_bg));
        StatusBarUtils.StatusBarLightMode(this);
        init();
        // ATTENTION: This was auto-generated to handle app links.
        Intent appLinkIntent = getIntent();
        String appLinkAction = appLinkIntent.getAction();
        Uri appLinkData = appLinkIntent.getData();
    }

    private void init() {
        mShareId = getIntent().getStringExtra("shareId");
        if (!TextUtils.isEmpty(mShareId)) {
            mLlShare.setVisibility(View.VISIBLE);
            mTvShareId.setText(mShareId);
        }
        myTime = new MyTime(60000, 1000);
        mCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    isCheckbox = true;
                } else {
                    isCheckbox = false;
                }
            }
        });
        mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE);
        mInputLayoutPhone.getEditText().addTextChangedListener(textWatcherPhone);
        mInputLayoutPhotoCode.getEditText().addTextChangedListener(textWatcherPhoneCode);
        mInputLayoutCode.getEditText().addTextChangedListener(textWatcherCode);
        mInputLayoutPwd.getEditText().addTextChangedListener(textWatcherPwd);
        mBtRegister.setClickable(false);
//        EditTextUtil.setEditTextInhibitInputSpeChat(mPswEdit);
    }

   /* @Override
    public void initInjector() {
        DaggerRegisterComponent.builder()
                .registerModule(new Register
                Module(this))
                .build()
                .inject(this);
    }*/

    @Override
    public boolean isVerification() {
        String phone = getPhone();
        String pwd = getPwd();
        String code = getCode();
        String photoCode = getPhotoCode();
        if ("".equals(phone)) {
            ToastUitl.show("请输入手机号", Toast.LENGTH_SHORT);
            return false;
        } else if (phone.length() != 11) {
            ToastUitl.show("手机号码输入错误", Toast.LENGTH_SHORT);
            return false;
        } else if ("".equals(code)) {
            ToastUitl.show("请输入验证码", Toast.LENGTH_SHORT);
            return false;
        } else if ("".equals(photoCode)) {
            ToastUitl.show("请输入图形码", Toast.LENGTH_SHORT);
            return false;
        } else if ("".equals(pwd)) {
            ToastUitl.show("请输入密码", Toast.LENGTH_SHORT);
            return false;
        } else if (pwd.length() < 6) {
            ToastUitl.show("密码的长度为6-16位", Toast.LENGTH_SHORT);
            return false;
        } else if (pwd.length() > 16) {
            ToastUitl.show("密码的长度为6-16位", Toast.LENGTH_SHORT);
            return false;
        } else if (!PwdCheckUtil.isContainAll(pwd)) {
            ToastUitl.show("必须同时包含字母+数字的组合", Toast.LENGTH_SHORT);
            return false;
        }

        return true;
    }

//    @OnClick({R.id.relative_phone_del,R.id.relative_pwd_del})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.relative_phone_del:
//                mInputLayoutPhone.getEditText().setText("");
//                relativePhoneDel.setVisibility(View.GONE);
//                break;
//            case R.id.relative_pwd_del:
//                mInputLayoutPwd.getEditText().setText("");
//                relativePwdDel.setVisibility(View.GONE);
//        }
//    }

    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String str = sdf.format(date);
            System.out.println(str);
            mBtnCode.setText("重新发送" + millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            mBtnCode.setBackgroundResource(R.drawable.sytel_code_select);
            mBtnCode.setText(getResources().getString(R.string.send_code));
        }
    }


    @Override
    public String getPwd() {
        return mInputLayoutPwd.getEditText().getText().toString();
    }

    @Override
    public String getPhone() {
        return mInputLayoutPhone.getEditText().getText().toString();
    }

    @Override
    public String getCode() {
        return mInputLayoutCode.getEditText().getText().toString();
    }

    @Override
    public String getPhotoCode() {
        return mInputLayoutPhotoCode.getEditText().getText().toString();
    }

    @Override
    public String getShareId() {
        return mShareId;
    }


    @Override
    public void isPhone() {
//        if(isVerificationPhone()){
//            if(mBtnCode.getText().toString().equals(getResources().getString(R.string.send_code))){
        myTime.start();
        mBtnCode.setBackgroundResource(R.drawable.sytel_code);
//                mPresenter.sendSMSCode();
//            }
//        }

    }

    @Override
    public void toSuccess() {
        Intent intent = new Intent(getContext(), RegisterStepTwoActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     *
     */
    public boolean isVerificationPhone() {
        String phone = getPhone();
        String phoneCode = getPhotoCode();
        if ("".equals(phone)) {
            ToastUitl.show("请输入手机号码", Toast.LENGTH_SHORT);
            return false;
        } else if (phone.length() != 11) {
            ToastUitl.show("手机号码输入错误", Toast.LENGTH_SHORT);
            return false;
        } else if ("".equals(phoneCode)) {
            ToastUitl.show("请输入图形验证码", Toast.LENGTH_SHORT);
            return false;
        } else if (!Tools.checkCellphone(phone)) {
            ToastUitl.show("请输入正确手机号码", Toast.LENGTH_SHORT);
            return false;
        }
        return true;
    }

    @OnClick({R.id.bt_register, R.id.btn_code, R.id.checkbox, R.id.rl_quit, R.id.iv_xianshi, R.id.btn_agreement, R.id.btn_refresh, R.id.contact_im, R.id.relative_phone_del, R.id.relative_pwd_del})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.relative_phone_del:
                mInputLayoutPhone.getEditText().setText("");
                relativePhoneDel.setVisibility(View.GONE);
                break;
            case R.id.relative_pwd_del:
                mInputLayoutPwd.getEditText().setText("");
                relativePwdDel.setVisibility(View.GONE);
                break;
            case R.id.bt_register:
                if (isVerification()) {
                    if (isCheckbox) {
                        mPresenter.register();
                    } else {
                        ToastUitl.show("请勾选使用协议", Toast.LENGTH_SHORT);
                    }
                }
                break;
            case R.id.btn_code:
                if (isVerificationPhone()) {
                    if (mBtnCode.getText().toString().equals(getResources().getString(R.string.send_code))) {
                        mPresenter.isPhone();
                    }

                }
                break;
            case R.id.btn_agreement:
                Intent intent = new Intent(getContext(), CommonWebActivity.class);
                intent.putExtra("ExtraWebPath", "https://www.mifengs.com/mifengs_m/agreementoverlay");
                intent.putExtra("ExtraWebTitle", "网络服务和使用协议");
                startActivity(intent);
                break;
            case R.id.checkbox:
                break;
            case R.id.rl_quit:
                finish();
                break;
            case R.id.iv_xianshi:
                passwordTransformation();
                break;
            case R.id.btn_refresh:
                Date date = new Date();
                String d = date.toString();
                mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE + "?d=" + d);
                break;
            case R.id.contact_im:
                intent = new Intent(Intent.ACTION_VIEW, Uri.parse("tel:400-9683889"));
                startActivity(intent);
                break;
        }
    }

    private void passwordTransformation() {

        if (!mDisplayFlg) {
            // display password text, for example "123456"
            mInputLayoutPwd.getEditText().setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            mInputLayoutPwd.getEditText().setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        mDisplayFlg = !mDisplayFlg;

        mInputLayoutPwd.getEditText().postInvalidate();

        if (mDisplayFlg) {
            mIvXianshi.setImageResource(R.drawable.ic_xianshi);
        } else {
            mIvXianshi.setImageResource(R.drawable.ic_noxianshi);
        }

    }

    TextWatcher textWatcherPhone = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String photoCode = getPhotoCode();
            String code = getCode();
            String pwd = getPwd();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(photoCode) || TextUtils.isEmpty(code) || TextUtils.isEmpty(s)) {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_gray);
                mBtRegister.setClickable(false);
            } else {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_red);
                mBtRegister.setClickable(true);

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                relativePhoneDel.setVisibility(View.INVISIBLE);
            } else {
                relativePhoneDel.setVisibility(View.VISIBLE);
            }
        }
    };

    TextWatcher textWatcherPhoneCode = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String photo = getPhone();
            String code = getCode();
            String pwd = getPwd();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(photo) || TextUtils.isEmpty(code) || TextUtils.isEmpty(s)) {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_gray);
                mBtRegister.setClickable(false);
            } else {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_red);
                mBtRegister.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    TextWatcher textWatcherCode = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String photoCode = getPhotoCode();
            String phone = getPhone();
            String pwd = getPwd();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(photoCode) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(s)) {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_gray);
                mBtRegister.setClickable(false);
            } else {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_red);
                mBtRegister.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
    TextWatcher textWatcherPwd = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String photo = getPhone();
            String code = getCode();
            String pwd = getPwd();
            if (TextUtils.isEmpty(pwd) || TextUtils.isEmpty(photo) || TextUtils.isEmpty(code) || TextUtils.isEmpty(s)) {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_gray);
                mBtRegister.setClickable(false);
            } else {
                mBtRegister.setBackgroundResource(R.drawable.shape_round_bt_red);
                mBtRegister.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                relativePwdDel.setVisibility(View.INVISIBLE);
            } else {
                relativePwdDel.setVisibility(View.VISIBLE);
            }

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTime != null) {
            myTime.cancel();
        }
    }


}
